class Solution {
public:
    int maxSubarraySumCircular(vector<int>& nums) {
        int n = nums.size();
        vector<int> dp(n + 1);
        int ret1 = -0x3f3f3f3f;
        for(int i = 1; i <= n; i++)
        {
            dp[i] = max(dp[i - 1] + nums[i - 1], nums[i - 1]);
            ret1 = max(ret1, dp[i]);            
        }
        
        int ret2 = 0x3f3f3f3f;
        for(int i = 1; i <= n; i++)
        {
            dp[i] = min(dp[i - 1] + nums[i - 1], nums[i - 1]);
            ret2 = min(ret2, dp[i]);            
        }

        int sum = 0;
        for(int x : nums)
            sum += x;
        return sum == ret2 ? ret1 : max(ret1, (sum - ret2));
    }
};